package base.thread_JUC2.chapter03.demo03;

import java.util.concurrent.CountDownLatch;

/**
 * 会议现场发现人没来齐就等待参会者们聚齐
 *
 */
public class Videoconference implements Runnable {

	/**
	 * This class uses a CountDownLatch to control the arrivel of all
	 * the participants
	 */
	private final CountDownLatch controller;
	
	/**
	 * Constructor of the class. Initializes the CountDownLatch
	 * @param number The number of participants in the videoconference
	 */
	public Videoconference(int number) {
		controller=new CountDownLatch(number);
	}

	/**
	 * This method is called by every participant when he incorporates to the VideoConference
	 * @param participant
	 */
	public void arrive(String name){
		System.out.printf("%s 已到达会议现场.\n",name);
		// 计数器 -1
		controller.countDown();
		System.out.printf("VideoConference: 等待剩余  %d 个参会者们.\n",controller.getCount());
	}
	
	/**
	 * This is the main method of the Controller of the VideoConference. It waits for all
	 * the participants and the, starts the conference
	 */
	@Override
	public void run() {
		System.out.printf("VideoConference: 初始参会者们: %d 个.\n",controller.getCount());
		try {
			// Wait for all the participants
			controller.await();
			// Starts the conference
			System.out.printf("VideoConference: 所有参会者们聚齐了\n");
			System.out.printf("VideoConference: 开始会议...\n");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	
}
